package org.dromara.common.core.utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusiException;

import java.util.List;
import java.util.concurrent.*;

/**
 * 线程相关工具类.
 *
 * @author fly
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Threads {

    /**
     * sleep等待,单位为毫秒
     */
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            return;
        }
    }

    /**
     * 停止线程池
     * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
     * 如果仍然超時，則強制退出.
     * 另对在shutdown时线程本身被调用中断做了处理.
     */
    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                        log.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * 打印线程异常信息
     */
    public static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            log.error(t.getMessage(), t);
        }
    }

    /**
     * 等待处理结束
     *
     * @param executorCompletionService
     * @param asyncExecutors
     * @param futures
     * @param timeout
     * @param unit
     */
    public static void wait(ExecutorCompletionService executorCompletionService, ExecutorService asyncExecutors,
                            List<Future> futures, long timeout, TimeUnit unit) {

        for (Future future : futures) {
            Future<String> f = null;
            try {
                f = executorCompletionService.poll(timeout, unit);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }

            if (null != f) {
                try {
                    String str = f.get();
                    if (StringUtils.isNotEmpty(str)) {
                        throw new BusiException(str);
                    }
                } catch (InterruptedException e) {
                    throw new BusiException(e);
                } catch (ExecutionException e) {
                    throw new BusiException(e);
                }
            } else {
                throw new BusiException("子线程运行一段时间后，任务还没有完成");
            }
        }
        shutdownAndAwaitTermination(asyncExecutors);
    }
}
